package com.fancyy.scm.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.fancyy.scm.R;
import com.fancyy.scm.base.BaseActivity;
import com.fancyy.scm.base.adapter.BRBaseAdapter;
import com.fancyy.scm.base.annotation.Layout;
import com.fancyy.scm.base.annotation.Translucent;
import com.fancyy.scm.base.http.BRDataListener;
import com.fancyy.scm.base.http.BRDataTransport;
import com.fancyy.scm.bean.ErrorEnum;
import com.fancyy.scm.bean.ProgressTracking;
import com.fancyy.scm.databinding.DishiyeBBinding;
import com.fancyy.scm.databinding.DishiyeBinding;
import com.fancyy.scm.util.DialogUtil;
import com.google.gson.reflect.TypeToken;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.ArrayList;
import java.util.List;

import static com.fancyy.scm.BRConstant.SCANNING_LOAD_ERROR;
import static com.fancyy.scm.BRConstant.SCANNING_SUBMIT;
import static com.fancyy.scm.BRConstant.SCANNING_TRACKING;
import static com.fancyy.scm.BRConstant.SCANNING_TRACKING_B_DATA;
import static com.fancyy.scm.BRConstant.SCANNING_TRACKING_LIST;
import static com.fancyy.scm.BRConstant.SCANNING_TRACKING_RESET;
import static com.fancyy.scm.BRConstant.SUBMIT;

@Translucent
@Layout(R.layout.dishiye_b)
public class TrackingBActivity extends BaseActivity<DishiyeBBinding> {

    BRBaseAdapter adapter = new BRBaseAdapter();
    List<ProgressTracking.ProgressTrackingItem> list = new ArrayList<>();

    private boolean isErrorPopUp=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setNeedScan(true);
        super.onCreate(savedInstanceState);
        adapter.init(this, R.layout.item, list);
        getDataBinding().listView.setAdapter(adapter);

        String barCode = getIntent().getStringExtra("barCode");
        String model = getIntent().getStringExtra("model");
        String packageQty = getIntent().getStringExtra("packageQty");
        String currentQty = getIntent().getStringExtra("currentQty");

//        getDataBinding().scan.setText(barCode);
        getDataBinding().model.setText(model);
        getDataBinding().packageQty.setText(packageQty);
        getDataBinding().currentQty.setText(currentQty);

        loadShoeListData();
    }

    private void loadShoeListData() {
        //BRDataTransport.createGet(SCANNING_TRACKING_LIST + "?barCode=" + getIntent().getStringExtra("barCode"))
        BRDataTransport.create(SCANNING_TRACKING_LIST)
                .addParam("barCode",getIntent().getStringExtra("barCode"))
                .addParam("ScanType", getIntent().getStringExtra("type"))
                .addProgressing(this, "Progressing...")
                .execute(new BRDataListener<ProgressTracking>() {
                    @Override
                    public void onSuccess(ProgressTracking data) {
                        list.clear();
                        if (data != null && data.shoesInfo != null) {
                            list.addAll(data.shoesInfo);
                        }
                        getDataBinding().model.setText(data.model);
                        getDataBinding().packageQty.setText(data.packageQty);
                        getDataBinding().currentQty.setText(data.currentQty);
                        adapter.notifyDataSetChanged();
                    }
                }, ProgressTracking.class);
    }

    public void onScanningClick(View view) {
        if(!getPDA() && !isErrorPopUp) {
            Intent intent = new Intent(this, CaptureActivity.class);
            startActivityForResult(intent, 1);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1 && resultCode == RESULT_OK) {
            String code = data.getStringExtra(CodeUtils.RESULT_STRING);
            handleCode(code);
        }
    }

    private void handleCode(String code) {
        getDataBinding().scan.setText(code);
        BRDataTransport.create(SCANNING_TRACKING_B_DATA)
                .addParam("QRCode", getIntent().getStringExtra("barCode"))
                .addParam("Barcode", getDataBinding().scan.getText().toString())
                .addParam("CreateBy", getBRApplication().getUserInfo().userAccount)
                .addParam("ScanType", getIntent().getStringExtra("type"))
                .addProgressing(this, "Progressing...")
                .execute(new BRDataListener<ProgressTracking>() {
                    @Override
                    public void onSuccess(ProgressTracking data) {
                        list.clear();
                        if (data != null && data.shoesInfo != null) {
                            list.addAll(data.shoesInfo);
                        }
                        adapter.notifyDataSetChanged();
                        getDataBinding().model.setText(data.model);
                        getDataBinding().packageQty.setText(data.packageQty);
                        getDataBinding().currentQty.setText(data.currentQty);
                        playSound(R.raw.success);

                        //add by ridong 2019-05-20:如果扫描匹配完全，则自动submit
                        if(Integer.parseInt(data.packageQty) == Integer.parseInt(data.currentQty))
                        {
                            onSubmitClick(null);
                        }
                    }

                    @Override
                    public void onFail(int status, String failMessage) {
                        playSound(R.raw.error);
                        isErrorPopUp = true;
                        DialogUtil.showAlert(self(), "Error", failMessage, "OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                                loadErrorCodes();
                            }
                        });
                    }
                }, ProgressTracking.class);
    }

    @Override
    public void doScan(String data) {
        if(!isErrorPopUp)
            handleCode(data);
//        closeScan();
    }

    String remark;

    public void onResetClick(View view) {
        if (!getDataBinding().scan.getText().toString().equals("")) {

        }
        //BRDataTransport.createPost(SCANNING_TRACKING_RESET + "?barCode=" + getIntent().getStringExtra("barCode"))
        BRDataTransport.createPost(SCANNING_TRACKING_RESET)
                .addParam("barCode", getIntent().getStringExtra("barCode"))
                .addParam("ScanType", getIntent().getStringExtra("type"))
                .addProgressing(this, "Progressing...")
                .execute(new BRDataListener() {
                    @Override
                    public void onSuccess(Object data) {
                        setResult(RESULT_OK);
                        finish();
                    }
                });
    }

    public void onSubmitClick(View view) {
        //BRDataTransport.create(SUBMIT + "?barCode=" + getIntent().getStringExtra("barCode"))
        BRDataTransport.create(SUBMIT)
                .addParam("barCode", getIntent().getStringExtra("barCode"))
                .addParam("Operator", getBRApplication().getUserInfo().userAccount)
                .addParam("ScanType", getIntent().getStringExtra("type"))
                .addProgressing(this, "Progressing...")
                .execute(new BRDataListener() {
                    @Override
                    public void onSuccess(Object data) {
                        showToast("Full Match Success");
                        setResult(RESULT_OK);
                        finish();
                    }
                });
    }

    List<ErrorEnum> errorData;
    private void loadErrorCodes() {
        BRDataTransport.createGet(SCANNING_LOAD_ERROR + "?EnumCategory=7")
                .addProgressing(self(), getString(R.string.Progressing))
                .execute(new BRDataListener<List<ErrorEnum>>() {
                    @Override
                    public void onSuccess(List<ErrorEnum> data) {
                        errorData = data;
                        getDataBinding().submit.setVisibility(View.VISIBLE);
                        TextView t = findViewById(R.id.code);
                        t.setText(data.get(0).enumName);
                        remark = data.get(0).enumCode;
                    }
                }, new TypeToken<List<ErrorEnum>>(){});
    }

    public void onCancelClick(View view) {
        remark = null;
        getDataBinding().submit.setVisibility(View.GONE);
        isErrorPopUp = false;
    }

    public void onErrorCodeClick(View view) {
        DialogUtil.showList(self(), "Error Item", errorData, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int which) {
                remark = errorData.get(which).enumCode;
                TextView t = findViewById(R.id.code);
                t.setText(errorData.get(which).enumName);
                dialogInterface.dismiss();
            }
        }, true);
    }

    public void onErrorSubmitClick(View view) {
        getDataBinding().submit.setVisibility(View.GONE);
        submitNet();
        isErrorPopUp = false;
    }

    private void submitNet() {
        BRDataTransport.create(SCANNING_SUBMIT)
                .addProgressing(self(), getString(R.string.Progressing))
                .addParam("ShoesBarCode", getIntent().getStringExtra("barCode"))
                .addParam("OuterBoxCode", getDataBinding().scan.getText().toString())
                .addParam("CreateBy", getBRApplication().getUserInfo().userAccount)
                .addParam("IsMatch", remark == null ? 1 : 0)
                .addParam("Remark", remark)
                .execute(new BRDataListener<Object>() {
                    @Override
                    public void onSuccess(Object data) {
//                        if (remark == null) {
//                            showToast("Full Match Success");
//                        } else {
//                            showToast("Submit Success");
//                        }
                        showToast("Submit Success");
                        setResult(RESULT_OK);
                        //finish();
                    }
                }, Object.class);
    }
}
